var db = require("./db.js");

var autoIncrement = require('mongoose-auto-increment');   //自增ID 模块

var Schema = db.Schema; //  创建模型

var json2csv = require('json2csv');

autoIncrement.initialize(db);   //初始化

var infoSchema = new Schema({
  name: String,
  grade: String,
  department: String,
  dormitory: String,
  tel: String,
  qq: String,
  dues: {type: Boolean, default: false},
  harmonica: {
    money: {type: Boolean, default: false},
    color: {type: String, default: 0}
  },
  book: {
    money: {type: Boolean, default: false},
    receive: {type: Boolean, default: false}
  },
  badge: {
    color: {type: String, default: 0}
  },
  remark: {type: String, default: ""},
  moneytype: {type: Boolean, default: false},
  signup_time: {type: Date, default: Date.now},
  confirm_time: {type: Date, default: Date.now},
  registrar: String,
  place: String
});

infoSchema.plugin(autoIncrement.plugin, {
    model: 'info',   //数据模块，需要跟同名 x.model("Books", infoSchema);
    field: 'id',     //字段名
});


var infoModel = db.model('info', infoSchema);

var InfoController = {};

/**
 * 新社员注册
 * @param  {[type]}   name       [description]
 * @param  {[type]}   grade      [description]
 * @param  {[type]}   department [description]
 * @param  {[type]}   dormitory  [description]
 * @param  {[type]}   tel        [description]
 * @param  {[type]}   qq         [description]
 * @param  {Function} callback   [description]
 * @return {[type]}              [description]
 */
InfoController.signup = function(name, grade, department, dormitory, tel, qq, callback){
  var telPattern = /^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  var qqPattern = /^[1-9]\d{4,9}$/;

  if(!name || !grade || !department || !dormitory || !tel || !qq || !tel.match(telPattern) || !qq.match(qqPattern)){
    callback(203);
    return;
  }
  var data = {
    name: name,
    grade: grade,
    department: department,
    dormitory: dormitory,
    tel: tel,
    qq: qq,
  }
  infoModel.findOne({tel: tel, qq: qq},function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      if(result){
        callback(205);
        return;
      }else{
        var entity = new infoModel(data);
        entity.save(function(error, fluffy) {
          if(error){
            callback(201);
            return;
          }else{
            callback(200, fluffy.id);
            return;
          }
        });
      }
    }
  });
}

/**
 * 搜索相关人员
 * @param  {[type]}   condition 可以为电话qq和姓名
 * @param  {Function} callback  [description]
 * @return {[type]}             [description]
 */
InfoController.search = function(condition, callback){
  var telPattern = /^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  var idPattern = /^\d{1,10}$/;
  if(!condition){
    callback(203);
    return;
  }
  var data = {};
  if(condition.match(telPattern)){
    data = {tel: condition};
  }else if(condition.match(idPattern)){
    data = {id: condition};
  }else{
    data = {name: condition};
  }
  infoModel.find(data,function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      callback(200,result);
    }
  });
}

/**
 * 更新信息
 * @param  {[type]}   condition [description]
 * @param  {[type]}   data      [description]
 * @param  {[type]}   userDetail  修改管理员的信息
 * @param  {Function} callback  [description]
 * @return {[type]}             [description]
 */
InfoController.update = function(condition, data, userDetail, callback){
  infoModel.findOne({id: condition},function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      if(!result){
        callback(207);
        return;
      }else{
        data.confirm_time = Date.now();
        data.registrar = userDetail.name;
        data.place = userDetail.place;
        var update = {
          $set: data
        };
        infoModel.update({id: condition}, update, function(error, fluffy) {
          if(error){
            callback(201);
            return;
          }else{
            callback(200, fluffy);
            return;
          }
        });
      }
    }
  });
}

InfoController.getAmount = function(place, callback){
  var conditions = {};
  if(place != -1 && place !== null){
    conditions.place = place;
  }
  infoModel.count(conditions, function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      callback(200, result);
      return;
    }
  });
}

InfoController.getAllAmount = function(callback){
  var _this = this;
  var data = {
    amount: Number,
    place: []
  };
  _this.getAmount(-1, function(errorCode, result){
    data.amount = result;
    _this.getAmount(0, function(errorCode, result){
      data.place[0] = result;
      _this.getAmount(1, function(errorCode, result){
        data.place[1] = result;
        _this.getAmount(2, function(errorCode, result){
          data.place[2] = result;
          _this.getAmount(3, function(errorCode, result){
            data.place[3] = result;
            _this.getAmount(4, function(errorCode, result){
              data.place[4] = result;
              callback(200, data);
            });
          });
        });
      });
    });
  });
}

InfoController.saveToCvs = function(date, callback){
  var conditions = {};
  if(date != -1){

  }
  infoModel.find(conditions,function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      try {
        var fields = [
          {
            label: '编号',
            value: 'id',
          },
          {
            label: '姓名',
            value: 'name',
          },
          {
            label: '年级',
            value: 'grade',
          },
          {
            label: '学院',
            value: 'department',
          },
          {
            label: '宿舍',
            value: 'dormitory',
          },
          {
            label: '电话',
            value: 'tel',
          },
          {
            label: 'QQ',
            value: 'qq',
          },
          {
            label: '社费',
            value: 'dues',
          },
          {
            label: '口琴费',
            value: 'harmonica.money',
          },
          {
            label: '口琴颜色',
            value: function(row){
              var result;
              switch(row.harmonica.color){
              case '1':
                result = '红色';
                break;
              case '2':
                result = '蓝色';
                break;
              case '3':
                result = '黑色';
                break;
              case '4':
                result = '金色';
                break;
              default:
                result = '未领取口琴';
                break;
              }
              return result;
            }
          },
          {
            label: '教材费',
            value: 'book.money',
          },
          {
            label: '教材领取情况',
            value: 'book.receive',
          },
          {
            label: '徽章颜色',
            value: function(row){
              var result;
              switch(row.badge.color){
              case '1':
                result = '粉色';
                break;
              case '2':
                result = '蓝色';
                break;
              case '3':
                result = '蓝紫渐变';
                break;
              case '4':
                result = '粉紫渐变';
                break;
              default:
                result = '未领取徽章';
                break;
              }
              return result;
            }
          },
          {
            label: '备注',
            value: 'remark',
          },
          {
            label: '注册人',
            value: 'registrar',

          },
          {
            label: '注册地点',
            value: function(row){
              var result;
              switch(row.place){
              case '0':
                result = '信部';
                break;
              case '1':
                result = '桂园';
                break;
              case '2':
                result = '湖滨';
                break;
              case '3':
                result = '医学部';
                break;
              case '4':
                result = '其他';
                break;
              default:
                result = '未注册';
                break;
              }
              return result;
            }
          },
          {
            label: '支付方式',
            value: function(row){
              if(row.moneytype){
                return "支付宝";
              }else{
                return "现金"
              }
            }
          },
          {
            label: '注册时间',
            value: function(row){
              return getExcelDate(row.signup_time);
            }
          },
          {
            label: '确认时间',
            value: function(row){
              return getExcelDate(row.confirm_time);
            }
          },
        ];
        var csv = json2csv({
          data: result,
          fields: fields,
          // fieldNames: fieldNames,
          quotes: ''
        });
        callback(200, csv);

      } catch (err) {
        // Errors are thrown for bad options, or if the data is empty and no fields are provided.
        // Be sure to provide fields if it is possible that your data array will be empty.
        callback(201);
      }
    }
  });
}

function getExcelDate(ISODate){
  if(!ISODate){
    return "";
  }
  var date = new Date(ISODate);
  var c = [date.getFullYear(), date.getMonth()+1, date.getDate()];
  var t = [date.getHours(), date.getMinutes()];
  var result = c.join("/") + " " + t.join(":");
  return result;
}



module.exports = InfoController; //  与user集合关联
